using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;

namespace IrcClient.Tests
{
    static class Program
    {
        static void Main()
        {
            foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (!IsCustomAttributeApplied(type, typeof(TestFixtureAttribute)))
                    continue;

                MethodInfo setup = null;
                MethodInfo tearDown = null;
                var tests = new List<MethodInfo>();
                foreach (var method in type.GetMethods())
                {
                    if (IsCustomAttributeApplied(method, typeof(TestFixtureSetUpAttribute)))
                        setup = method;

                    if (IsCustomAttributeApplied(method, typeof(TestFixtureTearDownAttribute)))
                        tearDown = method;

                    if (IsCustomAttributeApplied(method, typeof(TestAttribute)))
                        tests.Add(method);
                }

                var subject = Activator.CreateInstance(type);
                
                try
                {
                    if (setup != null)
                        setup.Invoke(subject, null);

                    foreach (var test in tests)
                        try
                        {
                            test.Invoke(subject, null);
                        }
                        catch (TargetInvocationException e)
                        {
                            Console.WriteLine(e.InnerException);
                        }
                }
                finally
                {
                    if (tearDown != null)
                        tearDown.Invoke(subject, null);
                }
            }

            Console.ReadKey();
        }

        private static bool IsCustomAttributeApplied(ICustomAttributeProvider attributeProvider, Type attribute)
        {
            return attributeProvider.GetCustomAttributes(attribute, false).LongLength > 0;
        }
    }
}